package com.sdkj.recruit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.sdkj.recruit.common.Constants;
import com.sdkj.recruit.model.User;
import com.sdkj.recruit.service.IUserService;
import com.sdkj.recruit.util.FileUploadUtil;
import com.sdkj.recruit.util.FileUploadUtil.UploadFileItem;
import com.sdkj.recruit.util.MD5Util;
import com.sdkj.recruit.util.RandomUtil;
import com.sdkj.recruit.util.StringUtil;

import net.sf.json.JSONObject;


@Controller
@Path("/import")
public class ImportController {

    private Log logger = LogFactory.getLog(ImportController.class);

    @Autowired
    IUserService userService;


    @Path(value = "/user")
    @POST
    public JSONObject importUser(@Context
    final HttpServletRequest req, @Context
    final HttpServletResponse res) {

        JSONObject json = new JSONObject();
        final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(req);
        if (uploadFiles.length >= 1) {
            try {
                File file = uploadFiles[0].getInternalFile();
                String fileName = file.getName();
                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                InputStream in = new FileInputStream(file);
                Workbook hb = null;
                if (fileType.equals("xls")) {
                    hb = new HSSFWorkbook(in);
                }
                else if (fileType.equals("xlsx")) {
                    hb = new XSSFWorkbook(in);
                }
                else {
                    logger.info("鎮ㄧ殑鏂囨。鏍煎紡涓嶆纭紒");
                }
                Sheet sheet = hb.getSheetAt(0);
                List<User> list = new ArrayList<User>();
                int count = 0;
                for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                    Row row = sheet.getRow(rowIndex);
                    User user = new User();
                    String userName = getCellValue(row.getCell(0), true);
                    User u = userService.queryUserByName(userName);
                    if (u != null && StringUtil.isNotEmptyString(u.getUserId())) {
                    	// 鍒犻櫎鑰佹暟鎹紝璁板綍鏂版暟鎹�
                    	userService.deleteUserById(u.getUserId());
                    }
                    user.setUserName(userName);
                    user.setUserId(new RandomUtil().getRandomId());
                    user.setUserType(1);
                    String keyPassword = userName + Constants.USER_KEY + MD5Util.string2MD5("123456");
                    user.setPassword(MD5Util.string2MD5(keyPassword));
                    list.add(user);
                }
                userService.saveUsers(list);
                if (count > 1) {
                    json.put("result", "閲嶅" + count + " 涓枃浠�");
                }
                else {
                    json.put("result", "涓婁紶鎴愬姛");
                }
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }

    /**
     * 鍙栧崟鍏冩牸鐨勫��
     * 
     * @param cell
     *            鍗曞厓鏍煎璞�
     * @param treatAsStr
     *            涓簍rue鏃讹紝褰撳仛鏂囨湰鏉ュ彇鍊� (鍙栧埌鐨勬槸鏂囨湰锛屼笉浼氭妸鈥�1鈥濆彇鎴愨��1.0鈥�)
     * @return
     */
    private static String getCellValue(Cell cell, boolean treatAsStr) {
        if (cell == null) {
            return "";
        }

        if (treatAsStr) {
            // 铏界劧excel涓缃殑閮芥槸鏂囨湰锛屼絾鏄暟瀛楁枃鏈繕琚閿欙紝濡傗��1鈥濆彇鎴愨��1.0鈥�
            // 鍔犱笂涓嬮潰杩欏彞锛屼复鏃舵妸瀹冨綋鍋氭枃鏈潵璇诲彇
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }

        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        }
        else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        }
        else {
            return String.valueOf(cell.getStringCellValue());
        }
    }
}
